const {
  $global
} = require('../static/global')

const app = getApp()

module.exports = Behavior({
  data: {
    isPhoneFormDisabled: true,
    phoneIcon: $global.R.img.phoneIcon,
    passIcon: $global.R.img.passIcon,
  },
  methods: {
    phoneInitModel() {
      return {
        phone: '',
        code: '',
      }
    },
    phoneValidateRules() {
      return {
        phone: [
          $global.Reg.required({}),
        ].concat(
          $global.Reg.isPhone(),
        ),
        code: [
          $global.Reg.stringType({}),
        ],
      }
    },
    showPhoneFormErr(type) {
      if (type === 'phone') {
        $global.showToast('输入正确的手机号码', this, {})
      }
      if (type === 'code') {
        $global.showToast('验证码错误', this, {})
      }
    },
    phoneGetVerifyCode(e) {
      let verifyCode = this.selectComponent('#verifyCode')
      this.mtValidateLive((value, valid, res) => {
        let hasPhoneErr = this.mtHasError('phone', res.errors)
        if (hasPhoneErr) {
          this.showFormErr('phone')
        } else {
          verifyCode.run()
        }
      })
    },
    phoneHandleErrors(res) {
      if (Array.isArray(res.errors) && res.errors.length > 0) {
        if (res.errors[0].field === 'phone') {
          this.showFormErr('phone')
        }
        if (res.errors[0].field === 'code') {
          this.showFormErr('code')
        }
      }
    },
    phoneHandleLiveChange(liveData) {
      this.mtValidateLive((value, valid, res) => {
        console.d(value, valid, res)
        if (valid) {
          this.setData({
            isPhoneFormDisabled: false
          })
        } else {
          this.setData({
            isPhoneFormDisabled: true
          })
        }
      })
    },
    phoneShowError() {
      let self = this
      $global.Dialog.alert({
        selector: '#show-dialog',
        title: '验证提示',
        context: this,
        confirmButtonText: '去问题验证',
        closeOnClickOverlay: true
      }).then((dialog) => {
        console.d('确定提交')
        self.$redirectPage(`verify-question`)
      }).catch( () => {
        // console.d('关闭')
        if (self.onPhoneDialogCancel) {
          self.onPhoneDialogCancel()
        }
      })
    },
    phoneOnDialogClose() {
      // console.d('phoneOnDialogClose')
    },
    phoneHandleSubmit(value, valid, res, options = {}) {
      let op = Object.assign({
        showDefaultPhoneError: true,
        type: 0,
        query: ''
      }, options)
      console.d('phoneHandleSubmit', value, valid, res, op)
      let self = this
      if (valid) {
        $global.Auth.wxLogin().then(wxLoginInfo => {
          /**
           * uid    用户openid
           * mobile 手机号
           * code  手机验证码
           */
          console.d('redirect my-detail-form')
          if (op && op.onComplete) {
            op.onComplete()
          }
          $global.Api.registerStudent({
            uid: wxLoginInfo.code,
            mobile: value.phone,
            code: value.code,
          }, {}, op.type, op.query).then((res) => {
            console.d('redirect my-detail-form end', res)
            if (!res || !res.hasOwnProperty('code')) {
              return Promise.reject(new Error(res ? res.msg : ''))
            }

            if (res.code === 20000) {
              // 确保code能用
              return $global.Auth.wxLogin()
            }
            else if (res.code === 61003) {
              // 61003 注册时可用
              return $global.Auth.wxLogin()
            }
            else {
              return Promise.reject(new Error(res ? res.msg : ''))
            }
          }).then((wxLoginInfo) => {
            let appendData = {}
            if (op.tokenCreateNeed) {
              appendData = op.tokenCreateNeed(appendData, value)
            }
            return $global.Api.commonTokenCreate(wxLoginInfo.code, {}, appendData)
          }).then((res) => {
            if (res && res.data && res.code === 20000) {
              $global.Auth.setToken(res.data.token)
              self.$redirectPage('my-detail-form?type=add&action=add')
            } else {
              return Promise.reject(new Error(res ? res.msg : ''))
            }
          }).catch((e) => {
            console.error('注册失败', e.message, e)
            if (e.message.indexOf('手机号验证失败') > -1) {
              if (op.showDefaultPhoneError) {
                self.phoneShowError()
              }
            } else {
              if (!e || !e.message) {
              }
            }
            if (op.onError) {
              op.onError(e)
            }
          }).finally(() => {
            if (op && op.onFinally) {
              op.onFinally()
            }
          })

        })
      }
    }
  }
})
